const fs = require('fs')
const path = require('path')
const { app } = require('electron')
const log = require('./log')
const crypto = require('crypto');



const APP_DEBUG = !app.isPackaged

// 如果是开发环境，则使用相对路径
const BASE_PATH = app.isPackaged ? path.join(process.resourcesPath, '..') : path.join(__dirname, '..')
global.BASE_PATH = BASE_PATH


const Store = require('electron-store');
// 配置文件
const schema = {
  nickName: {
    type: "string",
    default: "",
  },
  closeType: {
    type: "string",
    enum: ["tray", "quit"],
    default: "tray",
  },
  port: {
    type: "number",
    minimum: 10000,
    default: 63010,
  },
  imageDownloadPath: {
    type: "string",
    default: 'https://pic.yzhfuture.com/',
  },
  logPath: {
    type: "string",
    default: app.getPath("logs"),
  },
  tempPath: {
    type: "string",
    default: app.getPath("userData"),
  },
  // 开机自启动
  autoLaunch: {
    type: "string",
    enum: ["enabled", "disabled"],
    default: "disabled",
  },
  // 等待生成pdf，页面渲染延迟时间 默认300ms
  waitRenderTime: {
    type: "number",
    default: 300,
    minimum: 100,
    maximum: 10000,
  },
};
const store = new Store({ schema });

// 根据应用名称命名缓存文件夹名称
const APP_DATA_DIR_NAME = app.getName() + '-AppData'

// 根据应用名称命名缓存文件名称
const TEMP_PATH = path.join(store.get('tempPath'), APP_DATA_DIR_NAME)
global.TEMP_PATH = TEMP_PATH
// 上传目录
const UPLOAD_PATH = path.join(TEMP_PATH, 'uploads')
global.UPLOAD_PATH = UPLOAD_PATH
// 图片目录
const IMAGES_PATH = path.join(TEMP_PATH, 'images')
global.IMAGES_PATH = IMAGES_PATH
// 网页目录
const WWW_PATH = path.join(BASE_PATH, 'www')
global.WWW_PATH = WWW_PATH
// 字体目录
const FONTS_PATH = path.join(WWW_PATH, 'fonts')
global.FONTS_PATH = FONTS_PATH


// 端口
const HTTP_PORT = store.get('port')
global.HTTP_PORT = HTTP_PORT
// 基础路径
const BASE_APP_URL = 'http://localhost:' + HTTP_PORT
global.BASE_APP_URL = BASE_APP_URL


// 初始化 文件
const initFile = () => {
  let pathList = [TEMP_PATH, UPLOAD_PATH, IMAGES_PATH, FONTS_PATH]
  for (let i = 0; i < pathList.length; i++) {
    if (!fs.existsSync(pathList[i])) {
      fs.mkdirSync(pathList[i], { recursive: true });
      log(pathList[i] + '创建成功')
    }
  }
}

// md5 加密函数
const md5 = (str) => {
  return crypto.createHash('md5').update(str).digest('hex');
}

module.exports = {
  initFile,
  md5,
  BASE_APP_URL,
  APP_DEBUG,
  HTTP_PORT,
  TEMP_PATH,
  UPLOAD_PATH,
  IMAGES_PATH,
  WWW_PATH,
  FONTS_PATH,
  APP_DATA_DIR_NAME,
  store
}
